package com.weetop.aklyscan.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonRecyclerAdapter;
import com.honeywell.aidc.AidcManager;
import com.honeywell.aidc.BarcodeFailureEvent;
import com.honeywell.aidc.BarcodeReadEvent;
import com.honeywell.aidc.BarcodeReader;
import com.honeywell.aidc.TriggerStateChangeEvent;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.weetop.aklyscan.R;
import com.weetop.aklyscan.base.BaseActivity;
import com.weetop.aklyscan.base.BaseUrl;
import com.weetop.aklyscan.base.mvp.BaseModel;
import com.weetop.aklyscan.bean.BaseObject;
import com.weetop.aklyscan.bean.FittingInfo;
import com.weetop.aklyscan.bean.InMatterItemBean;
import com.weetop.aklyscan.bean.InventoryOrderBean;
import com.weetop.aklyscan.bean.SerailBean;
import com.weetop.aklyscan.presenter.InventoryPresent;
import com.weetop.aklyscan.utils.BaseUtils;
import com.weetop.aklyscan.view.InventoryView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cc.shinichi.library.tool.utility.ui.ToastUtil;

public class InventoryActivity extends BaseActivity<InventoryPresent> implements InventoryView, BarcodeReader.BarcodeListener, BarcodeReader.TriggerListener {
    @BindView(R.id.verification)
    TextView verification;
    @BindView(R.id.record)
    TextView record;
    @BindView(R.id.type)
    TextView type;
    @BindView(R.id.code_pd)
    TextView code_pd;
    @BindView(R.id.code_type)
    TextView code_type;
    @BindView(R.id.tv_warehouse_code)
    TextView wareHouseCodeView;
    @BindView(R.id.tv_transit_code)
    TextView tv_transit_code;
    @BindView(R.id.model_type)
    TextView model_type;
    @BindView(R.id.zzxh_ll)
    LinearLayout zzxh_ll;
    @BindView(R.id.pj_name_ll)
    LinearLayout pj_name_ll;
    @BindView(R.id.chanpin_ll)
    LinearLayout chanpin_ll;
    @BindView(R.id.peijian_ll)
    LinearLayout peijian_ll;
    @BindView(R.id.chanpin_list_ll)
    LinearLayout chanpin_list_ll;
    @BindView(R.id.peijian_list_ll)
    LinearLayout peijian_list_ll;
    @BindView(R.id.chanpin_re_ll)
    LinearLayout chanpin_re_ll;
    @BindView(R.id.peijian_re_ll)
    LinearLayout peijian_re_ll;
    @BindView(R.id.recyclerView_cp)
    RecyclerView recyclerView_cp;
    @BindView(R.id.recyclerView_pj)
    RecyclerView recyclerView_pj;
    @BindView(R.id.recyclerView1)
    RecyclerView recyclerView1;
    @BindView(R.id.recyclerView2)
    RecyclerView recyclerView2;
    @BindView(R.id.status)
    TextView status;
    @BindView(R.id.num)
    TextView num;
    @BindView(R.id.peijian_no)
    EditText peijian_no;
    @BindView(R.id.peijian_num)
    EditText peijian_num;
    @BindView(R.id.peijian_name)
    TextView peijianNameView;
    @BindView(R.id.tv_zhongzhuan_1)
    TextView tv_zhongzhuan_1;
    @BindView(R.id.iv_zhongzhuan_1)
    ImageView iv_zhongzhuan_1;
    @BindView(R.id.tv_num)
    TextView tv_number;
    private CommonRecyclerAdapter<InventoryOrderBean.DataBean> orderAdapter1;
    private CommonRecyclerAdapter<InventoryOrderBean.DataBean> orderAdapterMatter;
    private List<InventoryOrderBean.DataBean> orderList1 = new ArrayList<>();
    private List<InventoryOrderBean.DataBean> orderListMatter = new ArrayList<>();
    private CommonRecyclerAdapter<SerailBean.DataBean> adapter1;
    private List<SerailBean.DataBean> list1 = new ArrayList<>();
    private List<InMatterItemBean> list2 = new ArrayList<>();
    private CommonRecyclerAdapter<InMatterItemBean> adapter3;

    private String mOrderCode;

    @Override
    protected InventoryPresent createPresenter() {
        return new InventoryPresent(this, this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inventory);
        ButterKnife.bind(this);
        recyclerView_cp.setLayoutManager(new LinearLayoutManager(mActivity));
        recyclerView_pj.setLayoutManager(new LinearLayoutManager(mActivity));
        code_type.setTag(0);
        orderAdapter1 = new CommonRecyclerAdapter<InventoryOrderBean.DataBean>(mActivity, R.layout.item_inventory_order_cp, orderList1) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, InventoryOrderBean.DataBean item, int position) {
                helper.setText(R.id.tv_xuhao, position + 1 + "");
                helper.setText(R.id.model, item.getGoods_model());
                helper.setText(R.id.name, item.getGoods_name());
                helper.setText(R.id.yiru, item.getYp_num());
                helper.setText(R.id.weiru, item.getWp_num());
                helper.setText(R.id.totle, item.getTotal_num());
            }
        };
        orderAdapterMatter = new CommonRecyclerAdapter<InventoryOrderBean.DataBean>(mActivity, R.layout.item_inventory_order_cp, orderListMatter) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, InventoryOrderBean.DataBean item, int position) {
                helper.setText(R.id.tv_xuhao, position + 1 + "");
                helper.setText(R.id.model, item.getMatter_code());
                helper.setText(R.id.name, item.getMatter_name());
                helper.setText(R.id.yiru, item.getYp_num());
                helper.setText(R.id.weiru, item.getWp_num());
                helper.setText(R.id.totle, item.getCount_num());
            }
        };
        recyclerView_cp.setAdapter(orderAdapter1);
        recyclerView_pj.setAdapter(orderAdapterMatter);
        recyclerView1.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter1 = new CommonRecyclerAdapter<SerailBean.DataBean>(mActivity, R.layout.item_inventory_cp, list1) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, SerailBean.DataBean item, int position) {
                helper.setText(R.id.tv_xuhao, position + 1 + "");
                helper.setText(R.id.sn, item.getSerial_code());
                helper.setText(R.id.model, item.getGoods_model());
                helper.setText(R.id.name, item.getGoods_name());
                helper.setText(R.id.zzx, item.getTransit_code());
                helper.setText(R.id.hj_code, item.getWarehouse_coordinates());
                helper.setOnClickListener(R.id.btn_remove, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (BaseUtils.fastClick()) {
                            list1.remove(position);
                            adapter1.remove(position);
                        }
                    }
                });
            }
        };
        recyclerView1.setAdapter(adapter1);
        adapter3 = new CommonRecyclerAdapter<InMatterItemBean>(mActivity, R.layout.item_in_wx_peijian1, list2) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, InMatterItemBean item, int position) {
                helper.setText(R.id.tv_xuhao, position + 1 + "");
                helper.setText(R.id.tv_huopin_xinghao, item.getMatter_code());
                helper.setText(R.id.tv_huopin_mingcheng, item.getMatter_name());
                helper.setText(R.id.tv_xiangnei_huojia, wareHouseCodeView.getText().toString().trim());
                helper.setText(R.id.tv_zzx, tv_transit_code.getText().toString().trim());
                helper.setText(R.id.tv_peijian_num, item.getCount() + "");
                helper.setVisible(R.id.tv_zzx, (int) code_type.getTag() != 0);
                helper.setOnClickListener(R.id.btn_delete, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (list2.size() > position) {
                            adapter3.remove(item);
                            list2.remove(item);
                            adapter3.notifyDataSetChanged();
                        }
                    }
                });
            }
        };
        recyclerView2.setLayoutManager(new LinearLayoutManager(mActivity));
        recyclerView2.setAdapter(adapter3);
        type.setTag(0);
        status.setTag(0);
        model_type.setTag(0);
        initScan();
    }

    @Override
    public void getInto07Success(String matter_code, BaseModel<FittingInfo> o) {
        peijianNameView.setText(o.getData().getMatter_name());
        if (TextUtils.isEmpty(peijian_num.getText().toString().trim())) {
            return;
        }
        FittingInfo data = o.getData();
        InMatterItemBean matterItems = new InMatterItemBean();
        matterItems.setMatter_code(data.getMatter_code());
        matterItems.setMatter_name(data.getMatter_name());
        matterItems.setCount(Integer.valueOf(peijian_num.getText().toString().trim()));
        peijianNameView.setText(data.getMatter_name());
        list2.add(matterItems);
        adapter3.add(matterItems);
        recyclerView2.smoothScrollToPosition(list2.size());
        int total = 0;
        for (InMatterItemBean bean :
                list2) {
            total += bean.getCount();
        }
        tv_number.setText(total + "");
    }

    @Override
    public void getInto69Success(BaseModel<BaseObject<InventoryOrderBean>> o) {
        InventoryOrderBean bean = o.getData().getList_data();
        orderListMatter.clear();
        orderAdapterMatter.clear();
        orderListMatter.addAll(bean.getItems());
        orderAdapterMatter.addAll(orderListMatter);
        if (TextUtils.isEmpty(code_pd.getText().toString()))
            playRing("shujuyouxiao.mp3");
        code_pd.setText(mOrderCode);
        int f = 0;
        for (int i = 0; i < bean.getItems().size(); i++) {
            f = f + Integer.valueOf(bean.getItems().get(i).getCount_num());
        }
        num.setText(o.getData().getList_data().getNum_total());
    }

    @Override
    public void getInto48Success(BaseModel<InventoryOrderBean> o) {
        InventoryOrderBean bean = o.getData();
        orderList1.clear();
        orderAdapter1.clear();
        orderList1.addAll(bean.getItems());
        orderAdapter1.addAll(orderList1);
        if (TextUtils.isEmpty(code_pd.getText().toString()))
            playRing("shujuyouxiao.mp3");
        code_pd.setText(mOrderCode);
        int f = 0;
        for (int i = 0; i < bean.getItems().size(); i++) {
            f = f + Integer.valueOf(bean.getItems().get(i).getTotal_num());
        }
        num.setText(f + "");
    }

    @Override
    public void getserailSuccess(BaseModel<SerailBean> o) {
        SerailBean serailBean = o.getData();
        if (serailBean.getList().size() > 0) {
            if ((int) model_type.getTag() == 0 && list1.size() > 0) {
                if (!list1.get(0).getGoods_model().equals(serailBean.getList().get(0).getGoods_model())) {
                    ToastUtil.getInstance()._short(InventoryActivity.this, "型号不匹配");
                    playRing("shujuwuxiao.mp3");
                    return;
                }
            }
            SerailBean.DataBean dataBean = serailBean.getList().get(0);
            list1.add(dataBean);
            adapter1.add(dataBean);
            playRing("shujuyouxiao.mp3");
        } else {
            ToastUtil.getInstance()._short(InventoryActivity.this, "产品不存在");
            playRing("shujuwuxiao.mp3");
        }
    }

    @Override
    public void getInto49Success(BaseModel<String> o) {
        ToastUtil.getInstance()._short(InventoryActivity.this, "盘点完成");
        orderList1.clear();
        orderAdapter1.clear();
        orderAdapter1.notifyDataSetChanged();
        list1.clear();
        adapter1.clear();
        adapter1.notifyDataSetChanged();

        wareHouseCodeView.setText("");
        tv_transit_code.setText("");
        peijian_no.setText("");
        peijianNameView.setText("");
        peijian_num.setText("");
        list2.clear();
        adapter3.clear();
        adapter3.notifyDataSetChanged();
        num.setText("");

        if ((int) type.getTag() == 0) {
            mPresenter.Into48(code_pd.getText().toString().trim());
        } else {
            mPresenter.Into63(code_pd.getText().toString().trim());
        }

    }

    @Override
    public void showError(String msg) {
        super.showError(msg);
        ToastUtils.showShort(msg);
    }

    @Override
    public void onDataError() {
        super.onDataError();
        playRing("shujuwuxiao.mp3");
    }

    @OnClick({R.id.iv_back, R.id.chaxun, R.id.qingkong2, R.id.qingkong_transit, R.id.tv_confirm, R.id.verification, R.id.record, R.id.type, R.id.code_type, R.id.status, R.id.qingkong1, R.id.save, R.id.model_type})
    public void onViewClicked(View view) {
        String matterNo = peijian_no.getText().toString().trim();
        int codeType = Integer.parseInt(code_type.getTag().toString()) + 1;
        switch (view.getId()) {
            case R.id.qingkong_transit:
//                wareHouseCodeView.setText("");
                tv_transit_code.setText("");
                peijian_no.setText("");
                peijianNameView.setText("");
                peijian_num.setText("");
                list2.clear();
                adapter3.clear();
                adapter3.notifyDataSetChanged();
                playRing("qingkong.mp3");
                break;
            case R.id.qingkong2:
                //货架号清空
                wareHouseCodeView.setText("");
                tv_transit_code.setText("");
                peijian_no.setText("");
                peijianNameView.setText("");
                peijian_num.setText("");
                list2.clear();
                adapter3.clear();
                adapter3.notifyDataSetChanged();
                playRing("qingkong.mp3");
                break;
            case R.id.chaxun:
                if (TextUtils.isEmpty(matterNo)) {
                    ToastUtil.getInstance()._short(this, "配件编号不能为空");
                    return;
                }
                mPresenter.Into07(matterNo);
                break;
            case R.id.tv_confirm:
                String orderNo = code_pd.getText().toString().trim();
                String warehouseCode = wareHouseCodeView.getText().toString().trim();
                String transitCode = tv_transit_code.getText().toString().trim();
                String matterNum = peijian_num.getText().toString().trim();
                if (TextUtils.isEmpty(matterNo)) {
                    ToastUtil.getInstance()._short(this, "配件编号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(matterNum)) {
                    ToastUtil.getInstance()._short(this, "配件数量不能为空");
                    return;
                }
                if (TextUtils.isEmpty(orderNo)) {
                    ToastUtil.getInstance()._short(this, "订单号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(warehouseCode)) {
                    ToastUtil.getInstance()._short(this, "货架号不能喂空");
                    return;
                }
                if (TextUtils.isEmpty(transitCode) && codeType == 2) {
                    ToastUtil.getInstance()._short(this, "中转箱号不能为空");
                    return;
                } else {
//                    transitCode = "";
                }
                mPresenter.Into64(codeType + "", orderNo, warehouseCode, transitCode, matterNo, matterNum);
                break;
            case R.id.iv_back:
                AlertDialog.Builder normalDialog = new AlertDialog.Builder(InventoryActivity.this);
                normalDialog.setTitle("提示");
                normalDialog.setMessage("返回主页，当前数据将清除，是否返回");
                normalDialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });
                normalDialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                normalDialog.create().show();
                break;
            case R.id.record:
                if (TextUtils.isEmpty(code_pd.getText().toString().trim())) {
                    ToastUtil.getInstance()._short(InventoryActivity.this, "盘点编号不能为空");
                    return;
                }
                startActivity(new Intent(InventoryActivity.this, InventoryRecordActivity1.class)
                        .putExtra("type", (int) type.getTag())
                        .putExtra("order_sn", code_pd.getText().toString().trim()));
                break;
            case R.id.verification:
                if (TextUtils.isEmpty(code_pd.getText().toString().trim())) {
                    ToastUtil.getInstance()._short(InventoryActivity.this, "盘点编号不能为空");
                    return;
                }
                if ((int) type.getTag() == 0) {
                    startActivity(new Intent(InventoryActivity.this, InventoryVerificationActivity.class)
                            .putExtra("code", code_pd.getText().toString().trim())
                            .putExtra("type", "0"));
                } else {
                    startActivity(new Intent(InventoryActivity.this, InventoryVerificationActivity.class)
                            .putExtra("code", code_pd.getText().toString().trim())
                            .putExtra("type", "1"));
                }
                break;
            case R.id.type:
                XPopup.get(InventoryActivity.this).asCenterList("请选择类型", new String[]{"产品", "配件"},
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                type.setText(text);
                                type.setTag(position);
                                status.setText("未完成");
                                status.setTag(0);
                                if (position == 0) {
                                    chanpin_ll.setVisibility(View.VISIBLE);
                                    peijian_ll.setVisibility(View.GONE);
                                    chanpin_list_ll.setVisibility(View.VISIBLE);
                                    peijian_list_ll.setVisibility(View.GONE);
                                    chanpin_re_ll.setVisibility(View.VISIBLE);
                                    peijian_re_ll.setVisibility(View.GONE);
//                                    onBarcodeEvent("CPPD202201070001");
                                } else {
                                    chanpin_ll.setVisibility(View.GONE);
                                    peijian_ll.setVisibility(View.VISIBLE);
                                    chanpin_list_ll.setVisibility(View.GONE);
                                    peijian_list_ll.setVisibility(View.VISIBLE);
                                    chanpin_re_ll.setVisibility(View.GONE);
                                    peijian_re_ll.setVisibility(View.VISIBLE);
//                                    onBarcodeEvent("PJPD202109090036");
                                }
//
//                                handler.postDelayed(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        onBarcodeEvent("F1002akny022128C3655");
//                                    }
//                                }, 2000);
                            }
                        })
                        .show();
                break;
            case R.id.code_type:
                XPopup.get(InventoryActivity.this).asCenterList("请选择类型", new String[]{"货架编号", "中转箱号"},
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                code_type.setText(text);
                                code_type.setTag(position);
//                                onBarcodeEvent("PPS-PJ-B-1-111");
                                if (position == 0) {
                                    zzxh_ll.setVisibility(View.GONE);
                                    pj_name_ll.setVisibility(View.GONE);
                                    tv_zhongzhuan_1.setVisibility(View.GONE);
                                    iv_zhongzhuan_1.setVisibility(View.GONE);
                                } else {
                                    zzxh_ll.setVisibility(View.VISIBLE);
                                    pj_name_ll.setVisibility(View.VISIBLE);
                                    tv_zhongzhuan_1.setVisibility(View.VISIBLE);
                                    iv_zhongzhuan_1.setVisibility(View.VISIBLE);
                                }
                                adapter3.notifyDataSetChanged();
                            }
                        })
                        .show();
                break;
            case R.id.status:
                XPopup.get(InventoryActivity.this).asCenterList("请选择类型", new String[]{"未完成", "已完成"},
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                status.setText(text);
                                status.setTag(position);
                            }
                        })
                        .show();
                break;
            case R.id.model_type:
                XPopup.get(InventoryActivity.this).asCenterList("请选择类型", new String[]{"同型号", "异型号"},
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                model_type.setText(text);
                                model_type.setTag(position);
                            }
                        })
                        .show();
                break;
            case R.id.save:
                if ((int) type.getTag() == 0) {
                    String str = "";
                    for (int i = 0; i < list1.size(); i++) {
                        if (i == list1.size() - 1) {
                            str = str + list1.get(i).getSerial_code();
                        } else {
                            str = str + list1.get(i).getSerial_code() + ",";
                        }
                    }
                    mPresenter.Into49(code_pd.getText().toString().trim(), ((int) status.getTag() + 1) + "", str);
                } else {
                    try {
                        JSONArray jsonArray = new JSONArray();
                        JSONObject tmpObj = null;
                        if (list2.size() < 1) {
                            ToastUtils.showShort("无新增配件");
                            return;
                        }
                        for (int i = 0; i < list2.size(); i++) {
                            tmpObj = new JSONObject();
                            tmpObj.put("matter_code", list2.get(i).getMatter_code());
                            tmpObj.put("num", list2.get(i).getCount());
                            tmpObj.put("warehouse_coordinates", wareHouseCodeView.getText().toString().trim());
                            if (codeType == 2) {
                                tmpObj.put("transit_code", tv_transit_code.getText().toString().trim());
                            }
                            jsonArray.put(tmpObj);
                        }
                        mPresenter.Into65(code_pd.getText().toString().trim(), ((int) status.getTag() + 1) + "", jsonArray);
                    } catch (Exception e) {

                    }
                }
                break;
            case R.id.qingkong1:
                orderList1.clear();
                orderAdapter1.clear();
                orderAdapter1.notifyDataSetChanged();
                list1.clear();
                adapter1.clear();
                adapter1.notifyDataSetChanged();
                code_pd.setText("");
                num.setText("");
                playRing("qingkong.mp3");
                break;
        }
    }

    Handler handler = new Handler();

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            AlertDialog.Builder normalDialog = new AlertDialog.Builder(InventoryActivity.this);
            normalDialog.setTitle("提示");
            normalDialog.setMessage("返回主页，当前数据将清除，是否返回");
            normalDialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish();
                }
            });
            normalDialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            normalDialog.create().show();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }

    AidcManager manager;
    BarcodeReader barcodeReader;

    private void initScan() {
        //第一步：获取扫描资源，设置扫描参数，开启扫描功能
        AidcManager.create(InventoryActivity.this, new AidcManager.CreatedCallback() {
            @Override
            public void onCreated(AidcManager aidcManager) {
                manager = aidcManager;
                barcodeReader = manager.createBarcodeReader();
                try {
                    barcodeReader.claim(); //开启扫描功能
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //第二步：添加侧面扫描键事件监听和条码事件监听
                barcodeReader.addTriggerListener(InventoryActivity.this);
                barcodeReader.addBarcodeListener(InventoryActivity.this);
            }
        });
    }

    String huoCode;

    @Override
    public void getInto13Success(BaseModel<Object> o) {
        wareHouseCodeView.setText(huoCode);
        playRing("shujuyouxiao.mp3");
    }

    @Override
    public void onBarcodeEvent(BarcodeReadEvent barcodeReadEvent) {
        String barcodeData = barcodeReadEvent.getBarcodeData();
        onBarcodeEvent(barcodeData);
    }

    public void onBarcodeEvent(String barcodeData) {
        if ((int) type.getTag() == 0) {
            if (TextUtils.isEmpty(code_pd.getText().toString().trim())) {
                mOrderCode = barcodeData;
                mPresenter.Into48(barcodeData);
            } else {
                mPresenter.serail(barcodeData);
            }
        } else {
            if (TextUtils.isEmpty(code_pd.getText().toString().trim())) {
                mOrderCode = barcodeData;
                mPresenter.Into63(barcodeData);
            } else if (TextUtils.isEmpty(wareHouseCodeView.getText().toString().trim())) {
                huoCode = barcodeData;
                mPresenter.Into13(huoCode);
            } else {
                if (StringUtils.equals(code_type.getTag().toString(), "0")) {
                    //货架
                    if (TextUtils.isEmpty(peijian_no.getText().toString().trim())) {
                        peijian_no.setText(barcodeData);
                    }
                } else {
                    //中转箱
                    if (TextUtils.isEmpty(tv_transit_code.getText().toString().trim())) {
                        tv_transit_code.setText(barcodeData);
                    } else {
                        peijian_no.setText(barcodeData);
                    }
                }
            }
        }
    }

    @Override
    public void onFailureEvent(BarcodeFailureEvent barcodeFailureEvent) {
        System.out.println("失败：");
    }

    @Override
    public void onTriggerEvent(TriggerStateChangeEvent triggerStateChangeEvent) {
        System.out.println("按键：");
        if (triggerStateChangeEvent.getState() == true) {
            try {
                barcodeReader.light(true);        //开启补光
                barcodeReader.aim(true);        //开启瞄准线
                barcodeReader.decode(true);        //开启解码
            } catch (Exception e) {
                Toast.makeText(InventoryActivity.this, "开启扫描失败", Toast.LENGTH_SHORT).show();
            }
        } else if (triggerStateChangeEvent.getState() == false) {
            try {
                barcodeReader.light(false);        //关闭补光
                barcodeReader.aim(false);        //关闭瞄准线
                barcodeReader.decode(false);    //关闭解码
            } catch (Exception e) {
                Toast.makeText(InventoryActivity.this, "关闭扫描失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private AssetManager assetManager;
    private MediaPlayer player = new MediaPlayer();

    private void playRing(String fileName) {
        try {
            assetManager = getAssets();
            AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);
//            if (player.isPlaying()) {
            player.reset();
//            }
            player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            player.prepare();
            player.start();
            player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    player.stop();
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void playUrl(String fileName, final int i) {
        if (TextUtils.isEmpty(fileName)) {
            if (i == 1) {
                playRing("luruchenggong.mp3");
                return;
            } else {
                playRing("wuxiao.mp3");
                return;
            }
        }
        try {
            player.reset();
            if (!fileName.contains("http")) {
                player.setDataSource(BaseUrl.mp3Url + fileName);
            } else {
                player.setDataSource(fileName);
            }
            player.prepare();
            player.start();
            player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    if (i == 1) {
                        playRing("luruchenggong.mp3");
                    } else {
                        playRing("wuxiao.mp3");
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (barcodeReader != null) {
            try {
                barcodeReader.claim();        //开启扫描功能
            } catch (Exception e) {
//                Toast.makeText(this, "开启扫描失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (barcodeReader != null) {
            barcodeReader.release();        //释放扫描资源
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (barcodeReader != null) {
            barcodeReader.removeBarcodeListener(this);
            barcodeReader.removeTriggerListener(this);
            barcodeReader.close();
        }
        if (manager != null) {
            manager.close();
        }
    }
}
